<?php /* COMPANIES $Id: vw_depts.php,v 1.15.2.1 2006/07/31 11:54:15 nybod Exp $ */
##
##	Companies: View Projects sub-table
##
GLOBAL $AppUI, $company_id, $canEdit;

$q  = new DBQuery;
$q->addTable('departments');
$q->addQuery('departments.*, COUNT(contact_department) dept_users');
$q->addJoin('contacts', 'c', 'c.contact_department = dept_id');
$q->addWhere('dept_company = '.$company_id);
$q->addGroup('dept_id');
$q->addOrder('dept_parent, dept_name');
$sql = $q->prepare();
$q->clear();

// function renamed to avoid naming clash
function showchilddept_comp( &$a, $level=0 ) {
	global $AppUI;
	$s = '
	<td>
		<a href="index.php?m=departments&a=addedit&dept_id='.$a['dept_id'].'" title="'.$AppUI->_('edit').'">
			' . dPshowImage( 'images/edit.gif', 12, 12, '' ) . '
	</td>
	<td>';

	for ($y=0; $y < $level; $y++) 
	{
		if ($y+1 == $level)
			$s .= '<img src="images/corner-dots.gif" width="16" height="12" border="0">';
		else
			$s .= '<img src="images/shim.gif" width="16" height="12" border="0">';
	}

	$s .= '<a href="index.php?m=departments&a=view&dept_id='.$a['dept_id'].'">'.$a['dept_name'].'</a>';
	$s .= '</td>';
	$s .= '<td align="center">'.($a['dept_users'] ? $a['dept_users'] : '').'</td>';

	echo '<tr class="second">'.$s.'</tr>';
}

// function renamed to avoid naming clash
function findchilddept_comp( &$tarr, $parent, $level=0 ){
	$level = $level+1;
	$n = count( $tarr );
	for ($x=0; $x < $n; $x++) {
		if($tarr[$x]['dept_parent'] == $parent && $tarr[$x]['dept_parent'] != $tarr[$x]['dept_id']){
			showchilddept_comp( $tarr[$x], $level );
			findchilddept_comp( $tarr, $tarr[$x]['dept_id'], $level);
		}
	}
}

?>
<table border="0" cellpadding="7" cellspacing="0" width="100%" class="infopanel">
<tr>
	<td>
<? if ($canEdit) {
	showButton($AppUI->_( 'new department' ), 'index.php?m=departments&a=addedit&company_id='.$company_id);
} ?>
	</td>
</tr>
</table>
<table width="100%" border="0" cellpadding="2" cellspacing="0" class="list">
<tr><th>&nbsp;</th><th width="100%"><?=$AppUI->_( 'Name' )?></th><th><?=$AppUI->_( 'Users' )?></th></tr>
<tr class="second">
<?
$rows = db_loadList( $sql, NULL );
if (!count( $rows)) {
	echo '<td colspan="3">' . $AppUI->_('No data available') . '</td>';
}
?>
</tr>
<?
foreach ($rows as $row) {
	if ($row["dept_parent"] == 0) {
		showchilddept_comp( $row );
		findchilddept_comp( $rows, $row["dept_id"] );
	}
}
?>
</table>
